package com.lagou.utils;

import java.sql.Connection;
import java.sql.SQLException;

/**
 * @author: liufh
 * @create: 2021-07-11 16:21
 **/
public class ConnectionUtils {

    //将类创建交给容器管理，需将private构造器去掉
//    private ConnectionUtils() {
//    }
//
//    private static final ConnectionUtils connectionUtils = new ConnectionUtils();
//
//    public static ConnectionUtils getInstance() {
//        return connectionUtils;
//    }

    private ThreadLocal<Connection> threadLocal = new ThreadLocal<>();

    /**
     * 从当前线程获取连接
     */
    public Connection getCurrentThreadConn() throws SQLException {
        /**
         * 判断当前线程中是否已经绑定连接，如果没有绑定，需要从连接池获取一个连接绑定到当前线程
         */
        Connection connection = threadLocal.get();
        if (connection == null) {
            connection = DruidUtils.getInstance().getConnection();
            threadLocal.set(connection);
        }
        return connection;
    }

}
